package com.matchmealpha;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class TimelineActivity extends Activity implements OnClickListener {
	
	public static TimelineActivity ACTIVE_INSTANCE; 
    
    public static boolean CURRENTLY_DOWNLOADING; 

	private Button leftButton;
	private Button rightButton;
	private Button friendsButton;
	private Button matchmeButton;
	private Button youmeButton;
	private TextView name;
	private TextView errorMsg;
	private RelativeLayout loadingPanel;

	private boolean back;
	private int callerID; // 1 - recent, 2 - alert, 3 - timeline, 4 - friends
	private String curruser;
	private boolean relationship;

	private ListView timelineLayout;
	private List<Post> timelineList;
	private TimelineListAdapter timelineAdapter;

	private ProgressDialog loadingDialog;
	private String username;
	private String sessionid;

	private boolean myself;
	private int listingOrder;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		ACTIVE_INSTANCE = this; 
		super.onCreate(savedInstanceState);

		/*** Shared Pref ***/
		SharedPreferences settings = getSharedPreferences(
				"matchme_preferences", 0);
		username = settings.getString("username", "");
		sessionid = settings.getString("sessionid", "");

		/*** Saving Bundles Data ***/
		Bundle bund = this.getIntent().getExtras();
		if (bund != null) {
			this.back = bund.getBoolean("back",false);
			this.relationship = bund.getBoolean("relationship",false);
			this.callerID = bund.getInt("callerID");
			this.curruser = bund.getString("curruser");
		} /*
		 * else { this.back = false; this.callerID = MatchMeTabWidget.TIMELINE;
		 * this.curruser = username; }
		 */

		if (this.curruser.equals(username))
			myself = true;

		/*** Init ***/
		initLayout();
		initListener();

		/*** List View ***/
		timelineList = MatchMeTabWidget.timelineList;
		
		MatchMeTabWidget.timelineAdapter = new TimelineListAdapter(this, timelineList,
				this.callerID);
		timelineLayout.setAdapter(MatchMeTabWidget.timelineAdapter);
		displayLayout();


//		if (timelineList == null) {
//			MatchMeTabWidget.timelineList = new ArrayList<Post>();
//			timelineList = MatchMeTabWidget.timelineList;
//			MatchMeTabWidget.timelineAdapter = new TimelineListAdapter(this, timelineList,
//					this.callerID);
//			timelineLayout.setAdapter(timelineAdapter);
//			/*** Loading Screen ***/
//			loadingDialog = ProgressDialog.show(getParent(), "",
//					"Connecting...", true);
//			loadingDialog.show();
//			new TimelineTask().execute();
//		} else
//		{	
//			Log.d("SIZE", timelineList.size() + "");
//			timelineAdapter = new TimelineListAdapter(this, timelineList,
//					this.callerID);
//			timelineLayout.setAdapter(timelineAdapter);
//			displayLayout();
//			//timelineList.remove(0);
//			
//		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		//timelineAdapter = new TimelineListAdapter(this, timelineList,
		//		this.callerID);
		//timelineLayout.setAdapter(timelineAdapter);
		//timelineAdapter.notifyDataSetChanged();
	}

	private void initLayout() {
		listingOrder = 0;
		setContentView(R.layout.timeline_view);
		leftButton = (Button) this.findViewById(R.id.TimelineLeftButton);
		rightButton = (Button) this.findViewById(R.id.TimelineRightButton);
		friendsButton = (Button) this.findViewById(R.id.TimelineFriendsButton);
		matchmeButton = (Button) this.findViewById(R.id.TimelineMatchMeButton);
		youmeButton = (Button) this.findViewById(R.id.TimelineYouMeButton);
		name = (TextView) this.findViewById(R.id.TimelineName);
		errorMsg = (TextView) this.findViewById(R.id.TimelineError);
		timelineLayout = (ListView) this.findViewById(R.id.TimelineListView);
		loadingPanel = (RelativeLayout) findViewById(R.id.TimeLineLoadingPanel);
		
		if(!CURRENTLY_DOWNLOADING){
			 loadingPanel.setVisibility(View.GONE);
		}
		
		timelineLayout.setVisibility(View.INVISIBLE);
		friendsButton.setVisibility(View.INVISIBLE);
		matchmeButton.setVisibility(View.INVISIBLE);
		youmeButton.setVisibility(View.INVISIBLE);
		rightButton.setVisibility(View.INVISIBLE);
		name.setVisibility(View.INVISIBLE);
		errorMsg.setVisibility(View.GONE);
		if (!back)
			leftButton.setVisibility(View.INVISIBLE);
		if (relationship) {
			name.setText(curruser + " & " + username);
		} else {
			name.setText(curruser);
		}
	}

	private void displayErrorLayout() {
		errorMsg.setVisibility(View.VISIBLE);
		timelineLayout.setVisibility(View.INVISIBLE);
		friendsButton.setVisibility(View.INVISIBLE);
		matchmeButton.setVisibility(View.INVISIBLE);
		youmeButton.setVisibility(View.INVISIBLE);
		rightButton.setVisibility(View.INVISIBLE);
		name.setVisibility(View.INVISIBLE);
		timelineAdapter.notifyDataSetChanged();
		errorMsg.postInvalidate();
	}

	private void displayLayout() {
		errorMsg.setVisibility(View.GONE);
		timelineLayout.setVisibility(View.VISIBLE);
		friendsButton.setVisibility(View.VISIBLE);
		matchmeButton.setVisibility(View.VISIBLE);
		youmeButton.setVisibility(View.VISIBLE);
		rightButton.setVisibility(View.VISIBLE);
		name.setVisibility(View.VISIBLE);
		if (relationship) {
			matchmeButton.setVisibility(View.INVISIBLE);
			youmeButton.setVisibility(View.INVISIBLE);
			rightButton.setVisibility(View.INVISIBLE);
			friendsButton.setVisibility(View.INVISIBLE);
		}
		if (myself) {
			matchmeButton.setVisibility(View.INVISIBLE);
			youmeButton.setVisibility(View.INVISIBLE);
		} else {
			rightButton.setVisibility(View.INVISIBLE);
		}
		//timelineAdapter.notifyDataSetChanged();
		errorMsg.postInvalidate();
	}
	
	public  void hideLoadingPanel()
	{
		loadingPanel.setVisibility(View.GONE);
	}

	private void initListener() {
		if (back)
			leftButton.setOnClickListener(this);
		rightButton.setOnClickListener(this);
		friendsButton.setOnClickListener(this);
		matchmeButton.setOnClickListener(this);
		youmeButton.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case (R.id.TimelineRightButton):
			Intent intent = new Intent(this, SettingActivity.class);
			intent.putExtra("callerID", this.callerID);
			View view = MatchMeTabWidget
					.getCurrGroup(this.callerID)
					.getLocalActivityManager()
					.startActivity("SettingActivity",
							intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
					.getDecorView();
			MatchMeTabWidget.myReplaceView(view, this.callerID);
			break;
		case (R.id.TimelineLeftButton):
			MatchMeTabWidget.myBack(this.callerID);
			break;
		case (R.id.TimelineFriendsButton):
			// start friends activity?
			Intent intent3 = new Intent(this, FriendsListActivity.class);
			intent3.putExtra("back", true);
			intent3.putExtra("callerID", this.callerID);
			View view3 = MatchMeTabWidget
					.getCurrGroup(this.callerID)
					.getLocalActivityManager()
					.startActivity("FriendsListActivity",
							intent3.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
					.getDecorView();
			MatchMeTabWidget.myReplaceView(view3, this.callerID);
			break;
		case (R.id.TimelineMatchMeButton):
			// start camera
			// TODO send friend's uesrid?
			Intent in = new Intent(this, ShareActivity.class);
			in.putExtra("requester", this.username);
			startActivity(in);
			// start ShareActivit instead of changing tab view
			// MatchMeTabWidget.myTabHost().setCurrentTab(2);
			break;
		case (R.id.TimelineYouMeButton):
			// another timeline activity
			Intent intent5 = new Intent(this, TimelineActivity.class);
			intent5.putExtra("back", true);
			intent5.putExtra("callerID", this.callerID);
			intent5.putExtra("relationship", true);
			intent5.putExtra("curruser", curruser);
			View view5 = MatchMeTabWidget
					.getCurrGroup(this.callerID)
					.getLocalActivityManager()
					.startActivity("TimelineActivity",
							intent5.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
					.getDecorView();
			MatchMeTabWidget.myReplaceView(view5, this.callerID);
			break;
		}
	}



	private class TimelineTask extends AsyncTask<String, Void, Boolean> {

		protected Boolean doInBackground(String... data) {

			HttpRequest req = new HttpRequest(sessionid);
			String response;
			if (relationship) {
				response = req.sendPost(MatchMeTabWidget.MM_SERVER
						+ "/get_relationship/" + curruser + "/" + listingOrder,
						"");
			} else {
				response = req.sendPost(MatchMeTabWidget.MM_SERVER
						+ "/get_timeline/" + listingOrder, "");
			}
			if (MatchMeTabWidget.USER_AUTH_FAILURE.equals(response)
					|| MatchMeTabWidget.REQUEST_FAILURE.equals(response))
				return false;
			else if (response != null) {
				Scanner in = new Scanner(response).useDelimiter(";");
				Post post;
				while (in.hasNext()) {
					post = new Post();
					post.setPostID(in.nextInt());
					post.setUserID1(in.next());
					post.setUserID2(in.next());
					post.setLocation1(in.next());
					post.setLocation2(in.next());
					post.setStatus(in.next());
					post.setTime1(in.next());
					post.setTime2(in.next());
					post.setDescription1(in.next());
					post.setDescription2(in.next());
					//ShareActivity.getPostImage(post, sessionid);
					ShareActivity.getPostBitMapImage(post,sessionid);
					timelineList.add(post);
					Log.d("SIZE", timelineList.size() + "");
				}
				Log.d("TIME -----------------------", "Timeline list:" + timelineList.size());
				return true;
			} else
				return false;
		}

		protected void onPostExecute(Boolean result) {
			if(ACTIVE_INSTANCE != null)
			{
				if(ACTIVE_INSTANCE.loadingDialog != null)
				   ACTIVE_INSTANCE.loadingDialog.cancel();
			}
			
			if (result) {
				if (timelineList.size() <= 0) {
					Toast.makeText(getParent(), "No Image Found.",
							Toast.LENGTH_LONG);
				}
				displayLayout();
			} else {
				errorMsg.setText("Unable to connect. Please try again");
				displayErrorLayout();
			}
		}

	}
	
	public void showLoadingPanel() {
		loadingPanel.setVisibility(View.VISIBLE);	
	}

}
